package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.*;
import com.example.entity.authority.Party;
import com.example.entity.authority.PartyContract;
import com.example.entity.authority.PartyUser;
import com.example.ext.entity.ExtParty;
import com.example.mapp.*;
import com.example.service.PartyService;
import com.example.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by youkun on 2017/9/9.
 */
@Service
public class PartyServiceImpl  implements PartyService {

    private final static Logger logger = (Logger) LoggerFactory.getLogger(PartyServiceImpl.class);

	@Autowired
	private PartyMapp partyMapp;

	@Autowired
	private PromotionMapp promotionMapp;

	@Autowired
	private PartyUserMapp partyUserMapp;

	@Autowired
	private PartyContractMapp partyContractMapp;

	@Autowired
	private ElevatorMapp elevatorMapp;

	// 保存流水
	@Autowired
	private PointFlowMapp pointFlowMapp;

	// 用户
	@Autowired
	private SysUserMapp sysUserMapp;

	@Autowired
	private SystemMarkMapp systemMarkMapp;

    @Override
    public Map<String, Object> queryList(ExtParty extParty) {
        List<ExtParty> list =new ArrayList<>();
        Map<String,Object> map = new HashMap<String,Object>();
		try {
			/**
			 * 判断是否分页
			 */
			if (extParty.getCurrentPage() == null) {
				list = partyMapp.queryList(extParty);
				map.put("list", list);
			} else {
				// 判断是单位类型
				String credateDate = DateUtils.formatDate(new Date(), "yyyyMMdd");
				Page<ExtParty> page = PageHelper.startPage(extParty.getCurrentPage(), extParty.getPageSize());

				Map<String, Object> param = new HashMap<>();
				param.put("partyId", extParty.getId());
				param.put("credateDate", credateDate);
				extParty.setCredateDate(credateDate);

				if ("4".equals(extParty.getPartyType())) {
					if (StringUtils.isEmpty(extParty.getPartyLevel())) {
						return ResultUtil.returnError("查询失败,单位等级不能为空，请联系管理员", null);
					}
					// 区局\分局
					if ("1".equals(extParty.getPartyLevel())) {
						// 查询区局下的维保单位，使用单位
						list = partyMapp.findCensusInfoList(extParty);
					}
					// 区局\分局
					if ("2".equals(extParty.getPartyLevel())) {
						// 查询区局下的维保单位，使用单位
						list = partyMapp.findCensusInfoListArea(extParty);
					}

					if("3".equals(extParty.getPartyLevel())){
						list = partyMapp.findCensusInfoListAreaCity(extParty);
					}


				} else {
					PartyCensusInfo info = partyMapp.findCensusInfo(param);
					ExtParty party = new ExtParty();
					if (info != null) {
						party.setId(info.getPartyId());
						party.setPartyName(info.getPartyName());
						party.setPartyAddr(info.getPartyAddr());
						party.setPartyType(info.getPartyType());
						party.setEleCount(String.valueOf(info.getEleCount()));
						party.setContractNumber(String.valueOf(info.getContractNumber()));
						party.setProjectNum(String.valueOf(info.getProjectNum()));
						party.setUserJobNum(String.valueOf(info.getUserJobNum()));
						party.setUserCount(String.valueOf(info.getUserCount()));
						party.setSocialNum(String.valueOf(info.getSocialNum()));
					}
					list.add(party);
				}
				map.put("list", list);
				map.put("total", page.getTotal());
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("查询失败" + e.getMessage(), null);
		}
        return ResultUtil.returnSuccess("查询成功",map);
    }
/**
 * 查询上级机构
 */
	@Override
    public Map<String,Object> queryStrList(ExtParty extParty){
    	List<ExtParty> list = null;
		Map<String,Object> map = new HashMap<String,Object>();
		String id ="";
		try {
			// 判断是市还是局
			String limit = decideInfo(extParty.getId()+"");
			if ("0".equals(limit)) {
				// 0市
				list = partyMapp.queryStrListCity(extParty); // 市局
				map.put("list",list);
			}else if(extParty.getPartyLevel()==null){
				//System.out.println(extParty.getParentId());
				if(extParty.getParentId()!=null){
					list = partyMapp.queryStrListMainOrUsed(extParty.getParentId()); // 维保使用
				}
			} else{
				// 1、2 局和分局看局
				if ("2".equals(limit)) {
					list = partyMapp.queryStrListSub(extParty); //分局
					map.put("list",list);
				}else {
				list = partyMapp.queryStrListDis(extParty); // 区局
				map.put("list",list);}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("查询失败"+e.getMessage(),null);
		}
		map.put("list",list);
		return ResultUtil.returnSuccess("查询成功",map);
	}

	@Override
	public Map<String, Object> queryRandomList(Map map) {
		List<Map> list =null;
		Map<String,Object> map1 = new HashMap<String,Object>();
		try {
			Page<Map> page = PageHelper.startPage(
					Integer.parseInt(map.get("currentPage")+""),
					Integer.parseInt(map.get("pageSize")+""));
			list = partyMapp.queryRandomList(map);
			map1.put("list",list);
			map1.put("total",page.getTotal());

		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("查询失败"+e.getMessage(),null);
		}
		return ResultUtil.returnSuccess("查询成功",map1);
	}

    @Override
	@Transactional
    public Map<String, Object> add(Party party) {
        try {
            Party sys = partyMapp.queryByName(party.getPartyName());
            if(null==sys){
                int i = partyMapp.insert(party);
            }else {
                throw new Exception(party.getPartyName()+"已存在!");
            }

        }catch (Exception e){
        	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    @Transactional
    public Map<String, Object> update(Party party) {
        try {
            //查询数据是否存在
            ExtParty system = partyMapp.queryById(party.getId().toString());
            if(null==system){
				return ResultUtil.returnError(party.getPartyName()+"不存在，请联系管理员!",null);
            }
            if(party.getPartyName().equals(system.getPartyName())){
                partyMapp.update(party);
            }else{
                Party sys = partyMapp.queryByName(party.getPartyName());
                if(null==sys){
                    partyMapp.update(party);
                }else {
					return ResultUtil.returnError(party.getPartyName()+"已存在!",null);
                }
            }
        }catch (Exception e){
        	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("更新失败！",null);
        }finally {
			// 监管不计算
			// 暂时先注释掉
			/*if (!"4".equals(party.getLoggerType())) {
				// 通过唯一标识获取配置信息
				PointDefendInfoCache infoCache = new PointDefendInfoCache();
				PointDefend pointDefend = infoCache.
						getKeyByValue("unit_institutional_information");
				if (pointDefend != null) {
					// 获取必填字段
					List<String> strings = Arrays.asList(pointDefend.getMustBean()
							.split(","));
					double mark = ObjectBeanUtils.percentage(party, strings);
					BigDecimal bigDecimal = new BigDecimal(mark);
					mark = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP)
							.doubleValue();
					// 计算分数
					int number = (int) (mark * pointDefend.getMark());
					SystemMark systemMark = SystemPointUtil.
							findSystemMark(systemMarkMapp, party.getLoggerPartyId());
					if (systemMark == null) {
						systemMark = new SystemMark();
					}
					systemMark.setOrganInfoMark(number);
					systemMark.setPartyId(party.getLoggerPartyId());

					int insert = 0;
					// 查询是否有信息的
					if (systemMark.getId() != null) {
						// 修改
						insert = systemMarkMapp.update(systemMark);
					} else {
						// 新增
						insert = systemMarkMapp.insert(systemMark);
					}
					if (insert > 0) {
						// 计算总的积分并修改
						int i = SystemPointUtil.computerAfterUpdate(sysUserMapp, systemMark);
						// 插入流水信息
						PointFlow flow = new PointFlow();
						flow.setOperationType(pointDefend.getOperationType());
						flow.setOperationContent(pointDefend.getOperationContent());
						flow.setUserName(party.getLoggerPartyId());
						flow.setPartyName(party.getPartyName());
						flow.setIdentification(pointDefend.getIdentification());
						flow.setMark(i);
						flow.setFunction("完善本单位的机构信息");
						flow.setCreateBy(party.getLoggerPartyId());
						flow.setCreateDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
						pointFlowMapp.insertPointFlow(flow);
					}
				}
			}*/
		}
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    @Transactional
    public Map<String, Object> deleteById(String id) {
        try {
            partyMapp.deleteById(id);
        }catch (Exception e){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> queryById(String id) {
        ExtParty systemAuthor = null;
        try {
            systemAuthor = partyMapp.queryById(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",systemAuthor);
    }

    /**
     * 根据机构的id查询当前机构下的机构列表
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> queryByIdList(String id) {
        List<Party> partyList = new ArrayList<Party>();
        try{
            partyList = partyMapp.queryByPartyIdList(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",partyList);
    }

    /**
     * 根据机构的父id和类型查询当前机构下的机构列表
     * @param party
     * @return
     */
    @Override
    public Map<String, Object> queryByIdAndTypeList(Party party) {
        List<Party> partyList = new ArrayList<Party>();
        try{
        	if(party.getId()!=null){
				partyList = partyMapp.queryByIdAndTypeList(party);
			} else if ("4".equals(party.getPartyType()) && "1".equals(party.getLastManageParty())) {
				partyList = partyMapp.queryByLastManageAndTypeList(party.getPartyType());
			} else {
				partyList = partyMapp.queryByTypeList(party.getPartyType());
			}

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",partyList);
    }

	/**
	 * 导入机构
	 * @param file
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> importExcelParty(MultipartFile file,String parentId) {
		try {
			List<List<Object>> list = ExcelUtil.getListByExcel(file.getInputStream(),file.getOriginalFilename());
			//获取导入的文件
			if(list!=null && list.size()>0){
				for(int i = 0;i < list.size();i++){
					List listObject = list.get(i);
					if(listObject != null && ("序号".equals(listObject.get(0)+""))){
						continue;
					}
					if(listObject != null && listObject.size() > 0){

						//插入使用单位
						if( listObject.size()>=2 && listObject.get(1)!=null && !"".equals(listObject.get(1))){
							Party selectParty = partyMapp.queryByName(listObject.get(1).toString());
							if(selectParty==null){
								Party party = new Party();
								party.setPartyType("2");
								party.setPartyName(listObject.get(1).toString());
								party.setParentId(parentId);
								partyMapp.insert(party);
							}

						}
						//插入维保单位
						if( listObject.size()>=3 && listObject.get(2)!=null && !"".equals(listObject.get(2))) {
							Party selectParty = partyMapp.queryByName(listObject.get(2).toString());
							if(selectParty==null) {
								Party party = new Party();
								party.setPartyType("1");
								party.setPartyName(listObject.get(2).toString());
								party.setParentId(parentId);
								partyMapp.insert(party);
							}
						}
						//插入检验机构
						if( listObject.size()>=4 && listObject.get(3)!=null && !"".equals(listObject.get(3))) {
							Party selectParty = partyMapp.queryByName(listObject.get(3).toString());
							if(selectParty==null) {
								Party party3 = new Party();
								party3.setPartyType("3");
								party3.setPartyName(listObject.get(3).toString());
								party3.setParentId(parentId);
								partyMapp.insert(party3);
							}
						}
					}
				}
			}
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return ResultUtil.returnError(e.getMessage(),null);
		}
		return ResultUtil.returnSuccess("成功",null);
	}

	/**
	 * 根据机构来提示机构需要完善的信息
	 * @param partyId
	 * @return
	 */
	@Override
	public Map<String, Object> checkParytIdMessage(String partyId) {
		/** 查看机构下是否有用户如果没有积极提示
		 *  电梯安全管理人员档案》未完善，贵单位员工不能获得注册权限，是否立刻完善？
		 */
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			List<PartyUser> list = partyUserMapp.findByPartyIdAndType(partyId);
			if(list==null || list.size()<=0){
				map.put("user","电梯安全管理人员档案》未完善，贵单位员工不能获得注册权限，是否立刻完善");
			}
			//如果是监管部门还需要判断主题责任名册附件一
			ExtParty party = partyMapp.queryById(partyId);
			if(party!=null && party.getPartyType().equals("4")){
				List<Party> partyList = partyMapp.queryByPartyIdList(partyId);
				if(partyList==null||partyList.size()<=0){
					map.put("party","请完善主题责任名册附件一");
				}
			}
			//维保单位 使用单位都有合同
			if(party!=null && (party.getPartyType().equals("1")||party.getPartyType().equals("2"))){
				List<PartyContract> partyContract = partyContractMapp.queryByPartyId(partyId);
				if(partyContract==null||partyContract.size()<=0){
					map.put("partyContract","请完善合同");
				}
			}
			//使用单位还有电梯台帐 插入电梯表
			if(party!=null && party.getPartyType().equals("2")){
				List<Elevator> elevatorList = elevatorMapp.queryByUsedPartyId(partyId);
				if(elevatorList==null||elevatorList.size()<=0){
					map.put("elevator","请完善电梯台帐");
				}
			}
			// 判断分局还是局
			String type = decideInfo(partyId);
			map.put("type",type);


		}catch (Exception e){
			logger.error(e.getMessage(),e);
			return ResultUtil.returnError(e.getMessage(),null);
		}
		return ResultUtil.returnSuccess("成功",map);
	}

	@Override
	public Map<String, Object> queryByNameLk(Map map) {
		try {
			String name = "%"+map.get("partyName")+"%";
			List<Party> pl = partyMapp.queryByNameLk(name);
			if(pl!=null && pl.size()==1){
				return ResultUtil.returnSuccess("查到一家",pl);
			}else if(pl!=null && pl.size()>1){
				return ResultUtil.returnSuccess("根据单位名查到多家单位",pl);
			}else{
				return ResultUtil.returnSuccess("该单位在系统中不存在",null);
			}

		}catch (Exception e){
			logger.error("模糊查询机构失败："+e.getMessage(),e);
			return ResultUtil.returnError("根据单位名查查询出错了，请重试",null);
		}
	}

	/**
	 * 获取某级别所有的监管单位
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> queryPartyByPartyLevel(Map map) {
		List<Party> partyList = new ArrayList<Party>();
		try{
			if(map.get("partyLevel") != null && !"".equals(map.get("partyLevel"))){
				partyList = partyMapp.queryPartyByPartyLevel(map.get("partyLevel")+"");
			}else{
				return ResultUtil.returnError("参数为空",null);
			}

		}catch (Exception e){
			logger.error(e.getMessage(),e);
			return ResultUtil.returnError(e.getMessage(),null);
		}
		return ResultUtil.returnSuccess("成功",partyList);
	}

	@Override
	public Map<String, Object> queryCompanyNameList(Map companyName) {
		List<Map> companyNameList = new ArrayList<>();
		try {
			if(companyName !=null ){
			 companyNameList = partyMapp.queryCompanyNameList(companyName.get("companyNamePep").toString());
			}else {
				return ResultUtil.returnError("参数为空",null);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultUtil.returnSuccess("成功",companyNameList);

	}


	/**
	 * 查询所属分局
	* */
	@Override
	public Map<String, Object> queryChrssboard() {
	List<Map<String,String>> list = null;
	Map<String,List<Map<String,String>>> map = new HashMap<>();
		try {
			 list = partyMapp.queryChrssboard();
			 map.put("list",list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultUtil.returnSuccess("成功",map);
	}

	/**
	 * 获取是否是分局信息
	 * @param id
	 * @return
	 * @throws Exception
	 */
	private String decideInfo(String id) {
		String limit = "0";
		// 判断市或者局  通过传入Id判断  0是市级 1是局级 2 是分局
		List<Party> partys = partyMapp.decideBranchInfo(id);
		if (partys != null && partys.size() > 0) {
			List<Party> partyList = partyMapp.decideForEach(id);
			if (partyList != null && partyList.size() > 0) {
				limit = "0";
			} else {
				// 此时为局
				limit = "1";
			}
		} else {
			limit = "2";
		}
		return limit;
	}

	@Override
	public Map<String, Object> queryMaintenanceCompanyNameList(Map companyName) {
		List<Map> companyNameList = new ArrayList<>();
		try {
			if(companyName !=null ){
				companyNameList = partyMapp.queryMaintenanceCompanyNameList(companyName.get("companyNamePep2").toString());
			}else {
				return ResultUtil.returnError("参数为空",null);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultUtil.returnSuccess("成功",companyNameList);

	}

	@Override
	public Map<String, Object> queryUsePartCompanyNameList(Map companyName) {
		List<Map> companyNameList = new ArrayList<>();
		try{
			if(companyName != null){
				companyNameList = partyMapp.queryUsePartCompanyNameList(companyName.get("companyNamePep").toString());
			}
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			return ResultUtil.returnError(e.getMessage(),null);
		}
		return ResultUtil.returnSuccess("成功",companyNameList);
	}

	/**
	 * 通过等级查询所属分局
	 * @param parammap
	 * @return
	 */
	@Override
	public Map<String, Object> queryListByLevel(Map parammap) {
		List<Map<String,Object>> resultmap = new ArrayList<>();
		try {
			resultmap =  partyMapp.queryListByLevel(parammap);

		}catch (Exception e){
			return ResultUtil.returnError(e.getMessage(),null);
		}
		return ResultUtil.returnSuccess("成功",resultmap);
	}


	/**
	 * 每天1点跑机构信息
	 */
	@Override
	@Transactional
	public void partyCensusInfo() {

		// 存储所有人员
		Map<String, String> userList = new HashMap<>();
		List<Map<String, Object>> users = partyMapp.useParamList();
		for (Map<String, Object> objectMap : users) {
			if (StringUtils.isNotBlank(objectMap.get("id").toString())) {
				userList.put(objectMap.get("id").toString(), objectMap.get("userNum").toString());
			}
		}
		// 存储所有电梯个数
		Map<String, String> elevatorList = new HashMap<>();
		List<Map<String, Object>> elevators = elevatorMapp.groupByElevator();
		for (Map<String, Object> objectMap : elevators) {
			if (StringUtils.isNotBlank(objectMap.get("id").toString())) {
				elevatorList.put(objectMap.get("id").toString(), objectMap.get("eleNum").toString());
			}
		}

		// 存储合同数量
		Map<String, String> contractList = new HashMap<>();
		List<Map<String, Object>> contractlist = partyContractMapp.findContractList();
		for (Map<String, Object> objectMap : contractlist) {
			if (StringUtils.isNotBlank(objectMap.get("id").toString())) {
				contractList.put(objectMap.get("id").toString(), objectMap.get("numm").toString());
			}
		}

		//存储项目数量
		Map<String, String> objectHashMap = new HashMap<>();
		List<Map<String, Object>> objectlist = partyContractMapp.findObjectList();
		for (Map<String, Object> maps : objectlist) {
			if (StringUtils.isNotBlank(maps.get("id").toString())) {
				objectHashMap.put(maps.get("id").toString(), maps.get("numm").toString());
			}
		}

		// 查询从业人数
		Map<String, String> jobUsersMap = new HashMap<>();
		List<Map<String, Object>> jobNums = sysUserMapp.findJobNum();
		for (Map<String, Object> maps : jobNums) {
			if (StringUtils.isNotBlank(maps.get("id").toString())) {
				jobUsersMap.put(maps.get("id").toString(), maps.get("numm").toString());
			}
		}

		// 查询社保参保
		Map<String, String> socialMap = new HashMap<>();
		List<Map<String, Object>> socialNumList = sysUserMapp.findSocialNum();
		for (Map<String, Object> maps : socialNumList) {
			if (StringUtils.isNotBlank(maps.get("id").toString())) {
				socialMap.put(maps.get("id").toString(), maps.get("numm").toString());
			}
		}
		List<ExtParty> partyList = partyMapp.findPartyList(new ExtParty());
		if (partyList != null && partyList.size() > 0) {
			List<PartyCensusInfo> infoList = new ArrayList<>();
			String credateDate = DateUtils.formatDate(new Date(), "yyyyMMdd");
			// 将前天的数据删除掉
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DAY_OF_MONTH, -2);
			Date time = calendar.getTime();
			String beforeTime = DateUtils.formatDate(time, "yyyyMMdd");
			partyMapp.deleteCensusInfo(beforeTime);

			for (ExtParty party : partyList) {
				PartyCensusInfo info = new PartyCensusInfo();
				info.setPartyName(party.getPartyName());
				info.setPartyAddr(party.getPartyAddr());
				String id = String.valueOf(party.getId());
				// 电梯数量
				info.setPartyId(party.getId());


				String eleCount = elevatorList.get(id);
				if (StringUtils.isNotBlank(eleCount)) {
					info.setEleCount(Integer.valueOf(eleCount));
				}
				// 合同数量
				String contractNumber = contractList.get(id);
				if (StringUtils.isNotBlank(contractNumber)) {
					info.setContractNumber(Integer.valueOf(contractNumber));
				}
				// 项目数量
				String projectNum = objectHashMap.get(id);
				if (StringUtils.isNotBlank(projectNum)) {
					info.setProjectNum(Integer.valueOf(projectNum));
				}
				// 从业人数
				String userJobNum = jobUsersMap.get(id);
				if (StringUtils.isNotBlank(userJobNum)) {
					info.setUserJobNum(Integer.valueOf(userJobNum));
				}
				// 作业人数
				String userCount = userList.get(id);
				if (StringUtils.isNotBlank(userCount)) {
					info.setUserCount(Integer.valueOf(userCount));
				}
				// 社保数量
				String socialNum = socialMap.get(id);
				if (StringUtils.isNotBlank(socialNum)) {
					info.setSocialNum(Integer.valueOf(socialNum));
				}
				// 机构类型
				info.setPartyType(party.getPartyType());
				info.setCreateDate(credateDate);
				infoList.add(info);
			}
			// 进行保存
			if (infoList != null && infoList.size() > 0) {
				for (PartyCensusInfo censusInfo : infoList) {
					partyMapp.insertCensusInfo(censusInfo);
				}
			}
		}

	}
}
